What is find-root?
The find-root npm package is used to find the root directory of a Node.js project or module. This is typically the location where the 'package.json' file is located. It is useful when you have a deeply nested file structure and need to programmatically find the path to the project root.
What are find-root's main functionalities?
Find project root
This feature allows you to find the nearest directory containing a package.json file, which is considered the project's root directory.
const findRoot = require('find-root');
const root = findRoot('/path/to/some/deeply/nested/file');
console.log(root); // prints the path to the nearest directory containing a package.json
Other packages similar to find-root
pkg-dir
The 'pkg-dir' package provides similar functionality to 'find-root' by finding the closest package.json file in the directory tree. It is a more popular package with additional options and a promise-based API.
app-root-path
The 'app-root-path' package is used to determine the root path of the node application. Unlike 'find-root', which looks for the nearest package.json, 'app-root-path' uses a different heuristic that might be more suitable for certain applications.
root-require
The 'root-require' package allows you to require modules relative to the root of your Node.js project. It is similar to 'find-root' in that it helps with resolving paths in a project, but it is specifically tailored for requiring modules.
find-root
recursively find the closest package.json
usage
Say you want to check if the directory name of a project matches its
module name in package.json:
const path = require('path')
const findRoot = require('find-root')
const root = findRoot('/Users/jsdnxx/Code/find-root/tests')
const dirname = path.basename(root)
console.log('is it the same?')
console.log(dirname === require(path.join(root, 'package.json')).name)
You can also pass in a custom check function (by default, it checks for the
existence of package.json
in a directory). In this example, we traverse up
to find the root of a git repo:
const fs = require('fs')
const gitRoot = findRoot('/Users/jsdnxx/Code/find-root/tests', function (dir) {
return fs.existsSync(path.resolve(dir, '.git'))
})
api
findRoot: (startingPath : string, check?: (dir: string) => boolean) => string
Returns the path for the nearest directory to startingPath
containing
a package.json
file, eg /foo/module
.
If check
is provided, returns the path for the closest parent directory
where check
returns true.
Throws an error if no package.json
is found at any level in the
startingPath
.
installation
> npm install find-root
running the tests
From package root:
> npm install
> npm test
contributors
license
MIT. (c) 2017 jsdnxx